package com.guapi.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.guapi.dao.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDetailImpl implements UserDetails {
    private User user;
    private List<String> permissions;

    //3. 权限列表 {Security真正需要的权限} [这一项要提供给 Security 使用的]
    @JsonIgnore
    private transient List<SimpleGrantedAuthority> authorities;

    /**
     * 因为security自身的设计原因，角色权限前面需要添加ROLE前缀
     */
    private static final String ROLE_PREFIX = "ROLE_";

    public UserDetailImpl(User user, List<String> permissions) {
        this.user = user;
        setPermissions(permissions);
    }

    public UserDetailImpl(User user) {
        this.user = user;
    }

    private void setPermissions(List<String> permissions) {
        this.permissions = permissions;
        permissions.forEach(permission->{
            SimpleGrantedAuthority auth = new SimpleGrantedAuthority(ROLE_PREFIX+permission);
            authorities.add(auth);
        });
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (this.authorities!=null){
            return authorities;
        }
        //把permissions中字符串类型的权限信息转换成GrantedAuthority对象存入authorities中
        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        //AuthorityUtils.commaSeparatedStringToAuthorityList()
        return authorities;
    }

    @Override
    @JsonIgnore
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    @JsonIgnore
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return user.judgeIsLocked();
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isEnabled() {
        return user.judgeIsEnable();
    }
}
